//
//  SDPhotoBrowserViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/6/28.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDPhotoBrowserViewController.h"
#import "SDPhotoDetailInfoViewController.h"
#import "SDPhotoFilterViewController.h"
#import "SDPaientInfoMgr.h"
#import "SDTabBarController.h"
#import "SDPhotoInfo.h"
#import "VPTabBar.h"
#import "SDPhotoCollectionCell.h"
#import "AliyunOSSManager.h"
#import "SDAddPhotoInfoData.h"
#import "SDPhotoListData.h"
#import "SDDeletePhotoInfoData.h"
#import "SDPhotoFilterItem.h"

static NSString * const collectionCellIdentifier = @"UICollectionViewCell";
static NSString * const addMoreCollectionCellIdentifier = @"addMoreCollectionCellIdentifier";


typedef NS_ENUM( NSInteger, DELETE_PHOTO_TYPE)
{
    DELETE_PHOTO_TYPE_NONE                = 0,
    DELETE_PHOTO_TYPE_ALL   =  1,
    DELETE_PHOTO_TYPE_CLOUD_ONLY    = 2
};

@interface SDPhotoBrowserViewController()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,VPTabBarDelegate,SDFormBaseDataDelegate,SDBaseDataDelegate>
@property (nonatomic, strong) NSMutableArray        *photoOperationDataArray;
@property (nonatomic, strong) SDPhotoListData       *photoListData;
@property (nonatomic, strong) NSMutableArray        *selectedItemsArray;
@property (nonatomic, strong) NSMutableArray        *dateArray;
@property (nonatomic, strong) NSMutableDictionary   *photosDictionay;
@property (nonatomic, strong) NSArray               *searchArray;
@property (nonatomic, strong) SDPhotoFilterItem     *filterItem;

@property (nonatomic, strong) VPTabBar              *bottomBar;
@property (nonatomic, strong) UICollectionView      *collectionView;

@property (nonatomic, assign) BOOL                  needLogin;
@property (nonatomic, assign) BOOL                  editable;
@property (nonatomic, assign) float                 photoViewWidth;

@property (nonatomic, assign) BOOL                  isSearch;

@property (nonatomic, assign) DELETE_PHOTO_TYPE     delPhotoType;

///没有标签
@property (nonatomic, strong) UIView                *searchView;

@end

@implementation SDPhotoBrowserViewController

- (UIView *)searchView
{
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:self.view.bounds];
        UILabel *label = [[UILabel alloc] initWithFrame:_searchView.bounds];
        label.center = _searchView.center;
        label.text = @"目前没有相关标签的照片";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithRGB:0x666666];
        _searchView.hidden = true;
        [_searchView addSubview:label];
    }
    return _searchView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initData];
    [self initViews];
    [self.view addSubview:self.searchView];
    if (_selectedItemsArray == nil) {
        _selectedItemsArray = [NSMutableArray arrayWithCapacity:1];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginDidSuccessNotification:) name:kLoginMgrDidSucceedNotificaion object:nil];

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (!_needLogin) {
        [self loadDataFromDB];
    }
    _needLogin = NO;
}

-(void)initViews
{
    _photoViewWidth = ((kScreenWidth + 1) - 4) / 4;
    BOOL barHidden = [self navigationBarHidden];
    if (!barHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"照片管理"];
       // UIImage* fiterImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_tag.png");
       // [self.navBar customNaviLeftButton:self action:@selector(onFilter:) image:fiterImg];
        [self.navBar customNaviLeftButton:self action:@selector(onFilter:) title:@"筛选"];
        [self.navBar customNaviRightButton:self action:@selector(onSelectBtnClicked:) title:@"选择"];
    }
    
    
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:autoRectTableViewHaveBar(!barHidden) collectionViewLayout:flowLayout];
    self.collectionView.height -= MainTabBar_H;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    [self.collectionView registerClass:[SDPhotoCollectionCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    collectionViewLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 25);
    
    [self.view addSubview:self.collectionView];
}

-(UIView*)bottomBar
{
    VPTBarBtn* one = [[VPTBarBtn alloc] init];
    one.normalImg = [UIImage imageNamed:@"gallery_btn_sync.png"];
    one.selectImg = [UIImage imageNamed:@"gallery_btn_sync.png"];
    one.normalColor = [UIColor colorWithRGB:0x747F8B];
    one.selectColor = [UIColor colorWithRGB:0x747F8B];
    one.rightTitle = @"同步";
    
    VPTBarBtn* two = [[VPTBarBtn alloc] init];
    two.normalImg = [UIImage imageNamed:@"gallery_btn_delete.png"];
    two.selectImg = [UIImage imageNamed:@"gallery_btn_delete.png"];
    two.normalColor = [UIColor colorWithRGB:0x747F8B];
    two.selectColor = [UIColor colorWithRGB:0x747F8B];
    two.rightTitle = @"删除";
    
    
    _bottomBar = [[VPTabBar alloc] initWithPosY:0 btnList:[NSArray arrayWithObjects:one, two, nil]];
    _bottomBar.mydelegate = self;
    _bottomBar.backgroundColor = [UIColor colorWithRGB:0xffffff];
    [_bottomBar initMyContent];
    [one setIsSelectedMine:NO];
    [two setIsSelectedMine:NO];
    
    return _bottomBar;
}

-(void)initData
{
    _photoOperationDataArray = [[NSMutableArray alloc] init];
    
    _photoListData = [[SDPhotoListData alloc] init];
    _photoListData.delegate = self;
    [self loadDataFromNet];
    
    SDPaientInfoMgr* paientInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];
    [paientInfoMgr creatTable:[SDPhotoInfo class] tableName:kPhotoTableName keyName:nil primaryKey:nil];
}

-(void)loadDataFromNet
{
    BOOL isLogin = [[SDLoginManager sharedInstance] isLogin];
    if (isLogin) {
        _photoListData.pageNum = 1;
        [_photoListData reloadDataWithCache:NO];
    }
}

-(void)loadDataFromDB
{
    SDPaientInfoMgr* paientInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];

    _photosDictionay = [[NSMutableDictionary alloc] init];
    NSArray* allPhotos = [paientInfoMgr selectALL:[SDPhotoInfo class] tableName:kPhotoTableName];
    for (SDPhotoInfo* photoInfo in allPhotos) {
        NSString* dateStr = photoInfo.creationTime;
        NSMutableArray* tmpArr = [_photosDictionay objectForKey:dateStr];
        if(nil == tmpArr)
        {
            tmpArr = [NSMutableArray arrayWithCapacity:2];
            [_photosDictionay setObject:tmpArr forKey:dateStr];
        }
        [tmpArr addObject:photoInfo];
    }
    
    if(_photosDictionay.count > 0)
    {        
        NSArray* tmpArray = [[NSMutableArray arrayWithArray:[_photosDictionay allKeys]] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy/MM/dd/"];
            if (obj1 == [NSNull null]) {
                obj1 = @"0000/00/00";
            }
            if (obj2 == [NSNull null]) {
                obj2 = @"0000/00/00";
            }
            NSDate *date1 = [formatter dateFromString:obj1];
            NSDate *date2 = [formatter dateFromString:obj2];
            NSComparisonResult result = [date1 compare:date2];
            return result == NSOrderedAscending;
        }];
        _dateArray = [NSMutableArray arrayWithArray:tmpArray];
        self.navBar.backButton.enabled = YES;
        self.navBar.editBtn.enabled = YES;
    } else {
        [_dateArray removeAllObjects];
        
        if (!_editable) {
            self.navBar.backButton.enabled = NO;
            self.navBar.editBtn.enabled = NO;
        }
    }
    
    [self.collectionView reloadData];

}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)showLoadingWith:(NSString*)text
{
    [self finishLoading];
    [VPMBProgressHUD showIndicatorWithText:text];
}

- (void)finishLoading
{
    [VPMBProgressHUD hideIndicator];
}

- (void)failedLoading
{
    [self finishLoading];
    [VPMBProgressHUD showAttendAlert:@"上传失败" andIcon:nil];
}

-(void)cancelPhotoOperation
{
    if (!CHECK_VALID_ARRAY(_selectedItemsArray) && _editable) {
        [self onSelectBtnClicked:nil];
    }
}

#pragma mark UI Event
- (void)onFilter:(id)sender
{
    __weak typeof(self) weakSelf = self;
    SDPhotoFilterViewController* filterVC = [[SDPhotoFilterViewController alloc] init];
    [filterVC didFilterItem:^(SDPhotoFilterItem *item) {
        __strong SDPhotoBrowserViewController* strongSelf = weakSelf;
        strongSelf.filterItem  = item;
        
        NSString* condition;
        if (CHECK_VALID_STRING(item.mode)) {
            _isSearch = YES;
            condition = [NSString stringWithFormat:@"mode = '%@'",item.mode];
        }
        
        if (CHECK_VALID_STRING(item.position)) {
            _isSearch = YES;
            if (!CHECK_VALID_STRING(condition)) {
                condition = [NSString stringWithFormat:@"position = '%@'",item.position];
            } else {
                condition = [condition stringByAppendingFormat:@" OR position = '%@'",item.position];
            }
        }
        
        if (CHECK_VALID_STRING(item.status)) {
            _isSearch = YES;
            if (!CHECK_VALID_STRING(condition)) {
                condition = [NSString stringWithFormat:@"status LIKE '%%%@%%'",item.status];
            } else {
                condition = [condition stringByAppendingFormat:@" OR status LIKE '%%%@%%'",item.status];
            }
        }
        
//        if (CHECK_VALID_STRING(item.tag)) {
//            _isSearch = YES;
//            if (!CHECK_VALID_STRING(condition)) {
//                condit ion = [NSString stringWithFormat:@"tag = '%@'",item.tag];
//            } else {
//                condition = [condition stringByAppendingFormat:@" OR tag = '%@'",item.tag];
//            }
//        }
        
        if (CHECK_VALID_STRING(item.tag)) {
            _isSearch = YES;
            if (!CHECK_VALID_STRING(condition)) {
                condition = [NSString stringWithFormat:@"tag LIKE '%%%@%%'",item.tag];
            } else {
                condition = [condition stringByAppendingFormat:@" OR tag LIKE '%%%@%%'",item.tag];
            }
            
        }
        
        if (!CHECK_VALID_STRING(condition)) {
            _isSearch = NO;
        } else {
            _searchArray = [[SDPaientInfoMgr shareAGDatabaseManager] select:[SDPhotoInfo class] tableName:kPhotoTableName where:condition];
        }
        
        UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
        if (_isSearch) {
            if (_searchArray.count == 0) {
                [self.searchView setHidden:NO];
            } else {
                [self.searchView setHidden:YES];
            }
            collectionViewLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 0);
        } else {
            [self.searchView setHidden:YES];
            collectionViewLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 25);
        }
    }];
    //filterVC.filterItem = _filterItem;
    filterVC.filterItem = [[SDPhotoFilterItem alloc] init];
    [self presentViewController:filterVC animated:YES completion:nil];
}

- (void)onSelectBtnClicked:(id)sender
{
    SDTabBarController* tabBarCtrl = [[SDWindowManager defaultManager] getTabBarController];
    UIView* bottomBar = [tabBarCtrl.myTabBar viewWithTag:10001];
    if (bottomBar == nil) {
        bottomBar = [self bottomBar];
        [tabBarCtrl.myTabBar addSubview:bottomBar];
        bottomBar.tag = 10001;
    }
    _editable = !_editable;
    if (_editable) {
        bottomBar.hidden = NO;
        [ self.navBar.editBtn setTitle:@"取消" forState:UIControlStateNormal];
        
        if (CHECK_VALID_ARRAY(_selectedItemsArray)) {
            [_selectedItemsArray removeAllObjects];
        }
    } else {
        bottomBar.hidden = YES;
        [ self.navBar.editBtn setTitle:@"选择" forState:UIControlStateNormal];
    }
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (_isSearch) {
        return 1;
    }
    return CHECK_VALID_ARRAY(_dateArray) ? _dateArray.count : 0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_isSearch) {
        return CHECK_VALID_ARRAY(_searchArray) ? _searchArray.count : 0;
    }
    NSArray* photoList = [_photosDictionay  objectForKey:[_dateArray objectAtIndex:section]];
    return [photoList count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSArray* photoList;
    SDPhotoCollectionCell *cell;
    [cell setEditable:_editable];
    if (_isSearch) {
        photoList = _searchArray;
    } else {
         photoList = [_photosDictionay  objectForKey:[_dateArray objectAtIndex:section]];
    }
    SDPhotoInfo* photoInfo = photoList[row];
    
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIdentifier forIndexPath:indexPath];
    [cell setData:photoInfo];
    
//    if(indexPath.row < [photoList count]){
//         cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIdentifier forIndexPath:indexPath];
//        [cell setData:photoInfo];
//
//    } else {
//        UICollectionViewCell *addMoreCell = [collectionView dequeueReusableCellWithReuseIdentifier:addMoreCollectionCellIdentifier
//                                                                forIndexPath:indexPath];
//        addMoreCell.backgroundColor = [UIColor redColor];
//       // addMoreCell.delegate = self;
//        return addMoreCell;
//    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        
        UILabel* dateLabel = [headerView viewWithTag:10001];
        if (dateLabel == nil)
        {
            dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 50, 25)];
            dateLabel.textColor = [UIColor colorWithRGB:0x747f8b];
            [dateLabel setFont:[UIFont systemFontOfSize:11.f]];
            [headerView addSubview:dateLabel];
            dateLabel.tag = 10001;
        }
        
        NSString* dateStr = [_dateArray objectAtIndex:indexPath.section];
        dateLabel.text = [SDNSString getTimeStringFromDateString:dateStr];
        [dateLabel sizeToFit];
        dateLabel.top = (headerView.height - dateLabel.height)/2;
        
        reusableview = headerView;
    }
    
    return reusableview;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSArray* photoList;
    if (_isSearch) {
        photoList = _searchArray;
    } else {
        photoList = [_photosDictionay  objectForKey:[_dateArray objectAtIndex:section]];
    }

    if (CHECK_VALID_ARRAY(photoList)) {
        SDPhotoInfo* photoInfo = photoList[row];
        if (_editable) {
            NSIndexPath *imageIndexPath = [NSIndexPath indexPathForItem:row inSection:section];
            SDPhotoCollectionCell *photoCollectionCell = (SDPhotoCollectionCell *)[collectionView cellForItemAtIndexPath:imageIndexPath];
            [photoCollectionCell setOverlayViewHidden:!photoCollectionCell.overlayView.hidden];
            BOOL selected = !photoCollectionCell.overlayView.hidden;
            photoCollectionCell.photoInfo.selected = selected;
            if (selected) {
                if (![_selectedItemsArray containsObject:photoInfo]) {
                    [_selectedItemsArray addObject:photoInfo];
                }
            } else {
                if ([_selectedItemsArray containsObject:photoInfo]) {
                    [_selectedItemsArray removeObject:photoInfo];
                }
            }
        } else {
            SDPhotoDetailInfoViewController* detailInfoViewCtrl = [[SDPhotoDetailInfoViewController alloc] init];
            detailInfoViewCtrl.photoInfo = photoInfo;
            [self.navigationController pushViewController:detailInfoViewCtrl animated:YES];
        }
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(_photoViewWidth, _photoViewWidth);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.0;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    //float width = collectionView.frame.size.width;
    float width = kScreenWidth;
    float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
    int numberOfCells = (width + spacing) / (_photoViewWidth + spacing);
    int inset = (width + spacing - numberOfCells * (_photoViewWidth + spacing) ) / 2;
    
    return UIEdgeInsetsMake(0, inset, 0, inset);
}

#pragma mark - VPTabBarDelegate
-(void) selectBarBtnAtIndex:(NSInteger) index
{
    VPTBarBtn* tabBarItem = [_bottomBar.btnList objectAtIndex:index];
    [tabBarItem setIsSelectedMine:NO];
    __block BOOL flag = NO;
    if (index == 0) {
        SDLoginManager* loginMgr = [SDLoginManager sharedInstance];
        if (![loginMgr isLogin]) {
            _needLogin = YES;
            [self showLoginViewController];
            return;
        }
        
        if(!CHECK_VALID_ARRAY(_selectedItemsArray)){
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"选择要同步的照片" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        [self showLoadingWith:@"上传中"];
        for (SDPhotoInfo* photoInfo in _selectedItemsArray) {
            NSString* directory = [SDFile getDirectoryInCacheWithName:kPhotoDiretoryName];
            NSString *filePath = [directory stringByAppendingPathComponent:photoInfo.originalFileName];
            if ([SDFile fileExist:filePath]) {
                UIImage* image = [UIImage imageWithContentsOfFile:filePath];
                [[AliyunOSSManager sharedInstance] uploadObjectSyncWithFileName:photoInfo.originalFileName image:image completion:^(id data, NSError *error) {
                    if (!error) {
                        photoInfo.photoUrl = data;
                         BOOL isSuccess = [[SDPaientInfoMgr shareAGDatabaseManager] update:photoInfo tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];
                        if (isSuccess) {
                            flag = YES;
                            [self finishLoading];
                            
                            SDAddPhotoInfoData* addPhotoInfoData = [[SDAddPhotoInfoData alloc] init];
                            addPhotoInfoData.delegate = self;
                            addPhotoInfoData.photoInfo = photoInfo;
                            addPhotoInfoData.localPhotoId = photoInfo.id;
                            [addPhotoInfoData uploadFormDataWithUserInfo:nil];
                            
                            if (![_photoOperationDataArray containsObject:addPhotoInfoData]) {
                                [_photoOperationDataArray addObject:addPhotoInfoData];
                            }
                        } else {
                            [self failedLoading];
                        }
                    }else{
                        [self failedLoading];
                    }
                }];

            }
        }
    } else if (index == 1){
        
        SDLoginManager* loginMgr = [SDLoginManager sharedInstance];
        if (![loginMgr isLogin]) {
            _needLogin = YES;
            [self showLoginViewController];
            return;
        }
        
        if(!CHECK_VALID_ARRAY(_selectedItemsArray)){
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"选择要删除的照片" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"删除全部或仅云端" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *allAction = [UIAlertAction actionWithTitle:@"删除全部" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _delPhotoType = DELETE_PHOTO_TYPE_ALL;
            [_selectedItemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SDPhotoInfo* photoInfo = (SDPhotoInfo*)obj;
                
                [self removePhotoFromServer:photoInfo];
                
                [self removePhotoFromLocal:photoInfo];
            }];
            
            [_selectedItemsArray removeAllObjects];
            [self cancelPhotoOperation];
            
//           // if (flag)
//            {
//                [self loadDataFromDB];
//            }

        }];
        [alertController addAction:allAction];
        UIAlertAction* delServAction = [UIAlertAction actionWithTitle:@"删除云端" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _delPhotoType = DELETE_PHOTO_TYPE_CLOUD_ONLY;
            [_selectedItemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SDPhotoInfo* photoInfo = (SDPhotoInfo*)obj;
                [self removePhotoFromServer:photoInfo];
             //   [self removePhotoFromLocal:photoInfo];
                
             //   [self loadDataFromDB];

            }];
      
            
        }];
        [alertController addAction:delServAction];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
        
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    //if (flag)
    {
   //     [self loadDataFromDB];
    }
    
}

-(void)removePhotoFromServer:(SDPhotoInfo*)photoInfo
{
    //先删除server
    if (CHECK_VALID_STRING(photoInfo.photoUrl)) {
        SDDeletePhotoInfoData* delPhotoInfoData = [[SDDeletePhotoInfoData alloc] init];
        delPhotoInfoData.delegate = self;
        delPhotoInfoData.photoInfo = photoInfo;
        [delPhotoInfoData excuteHttpRequest];
        [_photoOperationDataArray addObject:delPhotoInfoData];
        
        [self showLoadingWith:@"删除中"];
    }

}

-(void)removePhotoFromLocal:(SDPhotoInfo*)photoInfo
{
    //删除本地
    if (CHECK_VALID_STRING(photoInfo.originalFileName)) {
        [SDFile deleteItem:photoInfo.originalFileName];
    }
    BOOL isSuccess = [[SDPaientInfoMgr shareAGDatabaseManager] deleteTableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];
    if (isSuccess) {
        if (CHECK_VALID_STRING(photoInfo.originalFileName)) {
            NSString* directory = [SDFile getDirectoryInCacheWithName:kPhotoDiretoryName];
            NSString *filePath = [directory stringByAppendingPathComponent:photoInfo.originalFileName];
            if ([SDFile fileExist:filePath]) {
                [SDFile deleteItem:filePath];
            }
        }
        [self removePhotoFromMemory:photoInfo];
        
    } else {
        
    }
}

-(void)removePhotoFromMemory:(SDPhotoInfo*)photoInfo
{
    NSString* dateStr = photoInfo.creationTime;
    NSMutableArray* tmpArr = [_photosDictionay objectForKey:dateStr];
    if(nil != tmpArr && [tmpArr containsObject:photoInfo])
    {
        [tmpArr removeObject:photoInfo];
        [_photosDictionay setObject:tmpArr forKey:dateStr];
        
        if (!CHECK_VALID_ARRAY(tmpArr)) {
            [_photosDictionay removeObjectForKey:dateStr];
        }
        
        [self.collectionView reloadData];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height)
//    {
//        if (_photoListData != nil && !_photoListData.pageOver) {
//            [_photoListData loadMoreData];
//        }
//    }
    
    if (CGRectIntersectsRect(scrollView.bounds, CGRectMake(0, self.collectionView.contentSize.height, CGRectGetWidth(self.view.frame), 40)) && self.collectionView.contentSize.height > 0)
    {
        if (_photoListData != nil && !_photoListData.pageOver) {
            [_photoListData loadMoreData];
        }
    }
}

#pragma mark -
#pragma mark -  Login Notifications
- (void)loginDidSuccessNotification:(NSNotification *)not
{
    [self loadDataFromNet];
}

#pragma mark- SDFromBaseDatDelegate
-(void) willUploadOfFormData:(SDFormBaseData*) formdata
{
    if ([formdata isKindOfClass:[SDAddPhotoInfoData class]])
    {
        [self showLoadingWith:@"上传中"];
    } else if ([formdata isKindOfClass:[SDDeletePhotoInfoData class]])
    {
        [self showLoadingWith:@"删除中"];

    }
}

-(void) formData:(SDFormBaseData*)formdata userInfo:(NSDictionary*) userInfo didFinishLoadWithError:(NSError*)error
{
    [self finishLoading];
    if (!error) {
        if ([formdata isKindOfClass:[SDAddPhotoInfoData class]])
        {
            SDAddPhotoInfoData* addPhotoInfoData = (SDAddPhotoInfoData*)formdata;
            SDPhotoInfo* photoInfo = addPhotoInfoData.photoInfo;
            SDPaientInfoMgr* dataBaseMgr = [SDPaientInfoMgr shareAGDatabaseManager];
            BOOL isSuccess = [dataBaseMgr update:photoInfo tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",addPhotoInfoData.localPhotoId]];
            
            if ([_selectedItemsArray containsObject:photoInfo]) {
                [_selectedItemsArray removeObject:photoInfo];
            }
            
            if (isSuccess) {
                [self.collectionView reloadData];
               
            } else {
                [self failedLoading];
            }
        } else if ([formdata isKindOfClass:[SDDeletePhotoInfoData class]]){
            SDDeletePhotoInfoData* delPhotoInfoData = (SDDeletePhotoInfoData*)formdata;
            SDPhotoInfo* photoInfo = delPhotoInfoData.photoInfo;
            if (_delPhotoType == DELETE_PHOTO_TYPE_CLOUD_ONLY) {
                SDPaientInfoMgr* dataBaseMgr = [SDPaientInfoMgr shareAGDatabaseManager];
                if ([_selectedItemsArray containsObject:photoInfo] ) {
                    if (CHECK_VALID_STRING(photoInfo.originalFileName)) {
                        photoInfo.photoUrl = nil;
                        BOOL isSuccess = [dataBaseMgr update:photoInfo tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];
                        if (isSuccess) {
                            [self loadDataFromDB];
                        }
                    } else {
                        [self removePhotoFromLocal:photoInfo];
                    }
          
                }
            } else {
                [self removePhotoFromMemory:photoInfo];
            }
            if ([_selectedItemsArray containsObject:photoInfo]) {
                [_selectedItemsArray removeObject:photoInfo];
            }
        }
  
    }else{
        if ([formdata isKindOfClass:[SDAddPhotoInfoData class]]){
            [VPMBProgressHUD showAttendAlert:@"上传失败" andIcon:nil];
        }
    }
    
    if ([formdata isKindOfClass:[SDAddPhotoInfoData class]] || [formdata isKindOfClass:[SDDeletePhotoInfoData class]])
    {
        if ([_photoOperationDataArray containsObject:formdata]) {
            [_photoOperationDataArray removeObject:formdata];
        }
    }
    
    [self cancelPhotoOperation];
}

#pragma mark -SDBaseDataDelegate
- (void)dataWillStartLoad:(SDBaseData*)model
{
    
}

- (void)data:(SDBaseData*)model didFinishLoadWithError:(NSError*)error nextDataType:(SDBaseDataType)nextDataType
{
    if (!error) {
        if ([model isKindOfClass:[SDPhotoListData class]]) {
            SDPaientInfoMgr* dataBaseMgr = [SDPaientInfoMgr shareAGDatabaseManager];
            for (SDPhotoInfo* infoItem in _photoListData.photoList) {
                NSArray* photoList = [dataBaseMgr select:[SDPhotoInfo class] tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",infoItem.id]];
                if (!CHECK_VALID_ARRAY(photoList)) {
                    BOOL success = [dataBaseMgr insert:infoItem tableName:kPhotoTableName];
                    if (success) {
                    }
                }
            }
            [self loadDataFromDB];
        }
    } else {
        
    }
}
@end
